package website.lucaswork.survey.mvc.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import website.lucaswork.survey.core.services.UserService;
import website.lucaswork.survey.mvc.forms.RegisterForm;

import javax.validation.Valid;


@Controller
@RequestMapping("/")
public class MainController extends SurveyWCI implements ErrorController {
    @Autowired
    UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model, @RequestParam(name = "action", required = false) String action) {
        if ("logout".equals(action)) {
            model.addAttribute("message", "You have logout successfully.");
        } else if ("error".equals(action)) {
            model.addAttribute("message", "Your username or password is wrong.");
        } else if ("register".equals(action)) {
            model.addAttribute("message", "Registration is done. Please login.");
        }
        return "login";
    }

    @RequestMapping("/error")
    public String error(Model model, @RequestParam(name = "action", required = false) String action) {
        if ("csrf".equals(action)) {
            model.addAttribute("message", "The page is expired. Try again.");
        }
        return "error";
    }

    @RequestMapping("/")
    public String entry() {
        return "redirect:/index";
    }

    @RequestMapping("/index")
    public String index(Model model) {
//		userService.createUser("a", "b", "c");
        return "index";
    }

    @RequestMapping(path = "/register", method = RequestMethod.GET)
    public String registerEntry(RegisterForm registerForm) {
        return "register";
    }

    @RequestMapping(path = "/register", method = RequestMethod.POST)
    public String registerProcessing(@Valid RegisterForm registerForm, BindingResult result) {
        if (result.hasErrors()) {
            return "register";
        }
        userService.createUser(registerForm.getUsername(), registerForm.getEmail(), registerForm.getPassword());
        return "redirect:/login?action=register";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}
